﻿using System;
using System.Web;
using System.Data;
using System.Linq;

namespace msBsc.WebUi
{
    public partial class wfCustOrder : msBsc.Cls.BPCustom
    {
        protected void Page_Load(object sender, EventArgs e)
        { 
            if (!IsPostBack)
            {
                ShowData();
            }
        }


        //s=0,为直接购买的，s=1为购物车，g为货物ID，b为货物购物车ID，q为数量,p1规格1的值
        private string s = "", g = "",b="",  p1 = "", p2 = "";
        private int q = 0;
        private DataSet dsList = null;
        private DataSet dsAcpList = null;
        private void GetFormParamByStr()
        {
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("s")))
            {
                s = this.Request.QueryString.Get("s");
            }
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("g")))
            {
                g = this.Request.QueryString.Get("g");
            }
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("b")))
            {
                b = this.Request.QueryString.Get("b");
            }
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("q")))
            {
                if (!int.TryParse(this.Request.QueryString.Get("q"), out q))
                {
                    q = 1;
                }
            }
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("p1")))
            {
                p1 = this.Request.QueryString.Get("p1");
            }
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("p2")))
            {
                p2 = this.Request.QueryString.Get("p2");
            }
        }

        private void ShowData()
        {
            GetFormParamByStr( );
            if (string.IsNullOrEmpty(s) || s != "0" && s != "1")
            {
                this.ToErrPage("当前没有找到需要下单的货品，请返回重新选择！");
                return;
            }
            using (msBsc.AppLogic.DataAlc.CBizShpCustomerInfo ocust = new AppLogic.DataAlc.CBizShpCustomerInfo())
            {
                int iUserScoreQty = ocust.GetUserScoreAllowUseQty(msBsc.SvRef.UserInfo.Operator);
                this.ExecJScript("$('#spnAllowUseScore').html('" + iUserScoreQty.ToString() + "');");
            }

            using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo objgoods = new AppLogic.DataAlc.CBizShpGoodsInfo())
            {
                using (msBsc.AppLogic.DataAlc.CBizShpCustomerReceipt odataobj = new AppLogic.DataAlc.CBizShpCustomerReceipt())
                {
                    dsAcpList = odataobj.SelectByUserNme(msBsc.SvRef.UserInfo.Operator);
                }
                string strPid = "";
                if (dsAcpList.Tables[0].Rows.Count > 0)
                {
                    DataRow[] arrrowtm = dsAcpList.Tables[0].Select("IS_DEFAULT=1");
                    if (arrrowtm.Length > 0)
                    {
                        strPid = arrrowtm[0]["PROVINCE_ID"].ToString();
                    }
                    else
                    {
                        strPid = dsAcpList.Tables[0].Rows[0]["PROVINCE_ID"].ToString();
                    }
                }
                dsList = objgoods.SelectGoodsForConfirmOrder(g, b, s, p1, p2, q, strPid);
                if (dsList.Tables[0].Rows.Count <= 0)
                {
                    this.ToErrPage("当前没有找到需要下单的货品，可能是选择的商品已失效或库存不足，请返回重新选择！");
                    return;
                }

                DataRow[] arrrowtem2 = dsList.Tables[0].Select("IS_DEL='1'");
                if (arrrowtem2.Length > 0)
                {
                    this.ExecJScript("$('#divErrShow').html('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson("商品已失效或库存不足，无法确认订单，请返回重新选择！") + "');");
                }

                this.ExecJScript("$('#txtGoodsId').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(g) + "');");
                this.ExecJScript("$('#txtCartId').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(b) + "');");
                this.ExecJScript("$('#txtSrcT').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(s) + "');");
                this.ExecJScript("$('#txtPubNId1').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(p1) + "');");
                this.ExecJScript("$('#txtPubNId2').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(p2) + "');");
                this.ExecJScript("$('#txtBuyQty').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(q.ToString()) + "');");
                this.ExecJScript("$('#txtPlaceId').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(strPid) + "');");

                ShowPayAmt();
                loadGoodsList(g, b, s, p1, p2, q, strPid);


            } 
        }

        private string strcalljs = "";
        private void loadGoodsList(string strGoodsId, string strBuyIds, string strSrcType, string strP1, string strP2, int intQ, string strProvince)
        {
            if (dsList == null)
            {
                using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo objgoods = new AppLogic.DataAlc.CBizShpGoodsInfo())
                {
                    dsList = objgoods.SelectGoodsForConfirmOrder(strGoodsId, strBuyIds, strSrcType, strP1, strP2, intQ, strProvince);
                }
            }

            string strjsontem1 = msBsc.AppLogic.Cfg.HttpTools.GetJsonByTable(dsList.Tables[0], "", "COMM_TENANT_ID,COMM_TENANT_NME,USER_NME"
                    , 1
                    , 1111
                    , "");
            this.ExecJScript(@" var _data= " + strjsontem1 + @" ; 
    jQuery.loadHtml('/Template/ConfirmOrderList.html').done(function (_rethtml) {
        var tpl = HtmlUtil.htmlDecode(_rethtml);
        laytpl(tpl).render(_data, function (render) {
            $(""#J_OrderList"").empty().html(render);
    " + strcalljs + @"
        });
    });
      "); 
        }

        //相同运费模版计算总件数
        System.Collections.Generic.Dictionary<string, decimal> dicShopLogistAmt = new System.Collections.Generic.Dictionary<string, decimal>();
        public void ShowPayAmt(bool blExecJs = true)
        {
            dicShopLogistAmt.Clear();
            if (dsList == null || dsList.Tables[0].Rows.Count <= 0)
            {
                if (blExecJs)
                {
                    this.ExecJScript("$('#J_ActualFee').html('0.00');");
                }
                return;
            }
            decimal decTotal = 0;
            int iScoreSum = 0;
            int iScorePriceSum = 0;
            //for (int i = 0; i < dsList.Tables[0].Rows.Count; i++)
            //{
            //    DataRow drGoods = dsList.Tables[0].Rows[i];
            //    decimal decAmt = decimal.Parse(drGoods["GOODS_AMT"].ToString() == string.Empty ? "0.00" : drGoods["GOODS_AMT"].ToString());
            //    decimal decYf = decimal.Parse(drGoods["FREIGHT"].ToString() == string.Empty ? "0.00" : drGoods["FREIGHT"].ToString());

            //    if (i == dsList.Tables[0].Rows.Count - 1 || dsList.Tables[0].Rows.Count > 1 && dsList.Tables[0].Rows[i]["COMM_TENANT_ID"].ToString() != dsList.Tables[0].Rows[i + 1]["COMM_TENANT_ID"].ToString())
            //    {
            //        decAmt = decAmt + decYf;
            //    }
            //    decTotal += decAmt;
            //}
            DataRow[] arrrowtem1 = dsList.Tables[0].Select("1=1");
            var newrows = from rowt in arrrowtem1
                          group rowt by rowt["COMM_TENANT_ID"].ToString() + "-" + rowt["LOGISTICS_TEMPLATE_ID"].ToString() into g
                          orderby g.Max(p => p["COMM_TENANT_ID"].ToString()) ascending, g.Max(p => p["LOGISTICS_TEMPLATE_ID"].ToString()) ascending
                          select new
                          {
                              g.Key,
                              strCOMM_TENANT_ID = g.Max(p => p["COMM_TENANT_ID"].ToString()),
                              strLOGISTICS_TEMPLATE_ID = g.Max(p => p["LOGISTICS_TEMPLATE_ID"].ToString()),
                              iGOODS_QTY = g.Sum(p => int.Parse(p["GOODS_QTY"].ToString())),
                              iQTY_FIRST = g.Max(p => int.Parse(p["QTY_FIRST"].ToString())),
                              iPRICE_FIRST = g.Max(p => decimal.Parse(p["PRICE_FIRST"].ToString())),
                              iQTY_ADD = g.Max(p => int.Parse(p["QTY_ADD"].ToString())),
                              iPRICE_ADD = g.Max(p => decimal.Parse(p["PRICE_ADD"].ToString())),
                              iGOODS_AMT = g.Sum(p => decimal.Parse(p["GOODS_AMT"].ToString())),
                              iSCORE_NUM = g.Sum(p => int.Parse(p["SCORE_NUM"].ToString())),
                              iGOODS_STRIKE_SCORE = g.Sum(p => int.Parse(p["GOODS_STRIKE_SCORE"].ToString()))
                          };

            //System.Collections.Generic.Dictionary<string, decimal> dicdealer = new System.Collections.Generic.Dictionary<string, decimal>();
            if (newrows != null && newrows.Count() > 0)
            {
                var aa = newrows.ToArray();
                decimal decYF = 0M, decTT = 0M;
                for (int i = 0; i < aa.Length; i++)
                {
                    //单模版运价
                    decimal decLogiAmt = 0M;
                    if (aa[i].iGOODS_QTY <= aa[i].iQTY_FIRST || aa[i].iQTY_ADD == 0)
                    {
                        decLogiAmt = aa[i].iPRICE_FIRST;
                    }
                    else
                    {
                        int iaddsum = (aa[i].iGOODS_QTY - aa[i].iQTY_FIRST) / aa[i].iQTY_ADD;
                        if ((aa[i].iGOODS_QTY - aa[i].iQTY_FIRST) % aa[i].iQTY_ADD > 0)
                        {
                            iaddsum = iaddsum + 1;
                        }
                        decLogiAmt = aa[i].iPRICE_FIRST + iaddsum * aa[i].iPRICE_ADD;
                    }
                    decTotal += aa[i].iGOODS_AMT + decLogiAmt;
                    iScoreSum += aa[i].iSCORE_NUM * aa[i].iGOODS_QTY;
                    iScorePriceSum += aa[i].iGOODS_STRIKE_SCORE * aa[i].iGOODS_QTY;

                    decYF += decLogiAmt;
                    decTT += aa[i].iGOODS_AMT;

                    if (i == aa.Length - 1 || 1 < aa.Length && aa[i].strCOMM_TENANT_ID != aa[i + 1].strCOMM_TENANT_ID)
                    {
                        dicShopLogistAmt.Add(aa[i].strCOMM_TENANT_ID, decYF);
                        if (blExecJs)
                        {
                            strcalljs += "setLogisAmt('" + aa[i].strCOMM_TENANT_ID + "'," + decYF.ToString() + "," + decTT.ToString() + ");";
                            this.ExecJScript("setLogisAmt('" + aa[i].strCOMM_TENANT_ID + "'," + decYF.ToString() + "," + decTT.ToString() + ");");
                        }
                        decYF = 0M;
                        decTT = 0M;
                    }

                    //if (dicdealer.ContainsKey(aa[i].strCOMM_TENANT_ID))
                    //{
                    //    dicdealer[aa[i].strCOMM_TENANT_ID] = dicdealer[aa[i].strCOMM_TENANT_ID] + decLogiAmt;
                    //}
                    //else
                    //{
                    //    dicdealer.Add(aa[i].strCOMM_TENANT_ID, decLogiAmt);
                    //}
                }
            } 


            if (blExecJs)
            {
                if (iScorePriceSum > 0)
                {
                    this.ExecJScript("$('#divscorehg').show();");
                }
                this.ExecJScript("$('#spnPAYABLE_AMT').html('" + decTotal.ToString() + "');");
                this.ExecJScript("$('#J_ActualFee').html('" + decTotal.ToString() + "');");
                this.ExecJScript("$('#spnScoreTotal').html('" + iScoreSum.ToString() + "');");
                this.ExecJScript("$('#txtPaidScoreQty').attr('max-score','" + iScorePriceSum.ToString() + "');");
                this.ExecJScript("$('#txtPaidScoreQty').attr('score-price','" + msBsc.SvRef.SysConst.decScoreUsePrice().ToString() + "');");
            }
        }

//        public string GetOrderListHtml()
//        {
//            if (dsList==null || dsList.Tables[0].Rows.Count <= 0)
//            { 
//                return "";
//            } 
//            System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();
//            for(int i=0;i<dsList.Tables[0].Rows.Count;i++)
//            {
//                DataRow drGoods = dsList.Tables[0].Rows[i];
//                decimal decAmt = decimal.Parse(drGoods["GOODS_STRIKE_PRICE"].ToString() == string.Empty ? "0.00" : drGoods["GOODS_STRIKE_PRICE"].ToString()) * q;
//                decimal decYf =  decimal.Parse(drGoods["FREIGHT"].ToString() == string.Empty ? "0.00" : drGoods["FREIGHT"].ToString());
//                sbHtml.Append(@"
//    <div  class=""order""> 
//        <input type=""hidden"" for=""DealerId"" value=""" + drGoods["COMM_TENANT_ID"].ToString() + @""">
//        <div  class=""orderInfo blue-line"">
//            <div>
//                <span class=""orderInfo-shoparea"">店铺：<a class=""orderInfo-shop J_MakePoint"" href=""/c_ShopView.htm?ID=" + drGoods["COMM_TENANT_ID"].ToString() + @"""
//                    target=""_blank"" title=""" + drGoods["COMM_TENANT_NME"].ToString() + @""" >" + drGoods["COMM_TENANT_NME"].ToString() + @"</a>
//                </span><span class=""orderInfo-seller"">卖家： <a class=""orderInfo-sellername J_MakePoint""
//                    href=""/c_ShopView.htm?ID=" + drGoods["COMM_TENANT_ID"].ToString() + @"""
//                    target=""_blank"" title=""" + drGoods["USER_NME"].ToString() + @""" >" + drGoods["USER_NME"].ToString() + @"</a>
//                    <span class=""J_WangWang"" >
//                    </span></span>
//            </div>
//        </div>
//        <div  class=""item blue-line clearfix"">
//        <input type=""hidden"" for=""GoodsId"" value=""" + drGoods["GOODS_ID"].ToString() + @""">
//        <input type=""hidden"" for=""NormsId"" value=""" + drGoods["PUB_NORMS_ID"].ToString() + @""">
//        <input type=""hidden"" for=""BuyQty"" value=""" + q + @""">
//            <div  class=""itemInfo item-title"">
//                <a target=""_blank"" href=""/c_GoodsView.htm?ID=" + drGoods["GOODS_ID"].ToString() + @""" title=""" + drGoods["GOODS_NME"].ToString() + @"""
//                    class=""itemInfo-link J_MakePoint"" >
//                    <span class=""item-pic""><span>
//                        <img class=""itemInfo-pic"" src=""" + drGoods["IMG_URL"].ToString() + @""">
//                    </span></span><span class=""itemInfo-title J_MakePoint"" >" + drGoods["GOODS_NME"].ToString() + @"</span> </a>
//                <div class=""itemInfo-sku"">
//                    <span>" + drGoods["NORMS_DESC"].ToString().Substring(1) + @"</span> <span></span>
//                </div>
//                <div class=""itemInfo-icons"">
//                </div>
//                <div class=""itemInfo-shop-info"">
//                    <a class=""orderInfo-sellername J_MakePoint"" href="""" target=""_blank"" title=""""></a>
//                    <span class=""J_WangWang"" >
//                    </span>
//                </div>
//                <p class=""c2c-extraInfo-container promo-extraInfo"">
//                </p>
//            </div>
//            <div class=""item-price"">
//                <span   class=""itemInfo price""><em class=""style-normal-small-black J_ItemPrice"">
//                    ￥" + drGoods["GOODS_STRIKE_PRICE"].ToString() + @"</em> </span>
//            </div>
//            <div  class=""quantity item-quantity"">
//                <p>
//                    " + q + @"</p>
//            </div>
//            <div class=""item-promo"">
//                <p>
//                    无优惠</p>
//            </div>
//            <div  class=""itemPay item-total"">
//                <p class=""itemPay-price price"">
//                    <em class=""style-normal-bold-red J_ItemTotal "">" + decAmt.ToString() + @"</em>
//                </p>
//            </div>
//            <div class=""item-form-desc blue-line clearfix"">
//                <div class=""item-form-eticketDesc"">
//                </div>
//            </div>
//        </div>
//        <div class=""order-extra"">
//            <div class=""order-user-info"">
//                <div   class=""memo"">
//                    <label>
//                        给卖家留言：</label>
//                    <textarea title=""选填：对本次交易的说明（建议填写已经和卖家达成一致的说明）"" class=""memo-input J_MakePoint c2c-text-default memo-close""  ></textarea>
//                         
//                </div>
//            </div>
//            <div class=""order-extra-info"">
//                <div  class=""deliveryMethod white-line"">
//                    <div class=""deliveryMethod-fee"">
//                        <span class=""price""><em class=""style-normal-bold-red"">" + drGoods["FREIGHT"].ToString() + @"</em></span>
//                    </div>
//                    <div class=""deliveryMethod-title"">
//                        运送方式：</div>
//                    <div class=""deliveryMethod-sel"">
//                        <ul class=""fare-group J_fareGroup_100 fare-list"">
//                            <li>
//                                <label class=""J_fare_id"" for=""fare169"">
//                                    <input name=""fare168"" class=""fare-radio J_fare_radio"" type=""radio"" checked=""checked"" >
//                                    普通配送</label> 
//                                <div class=""fare-date-picker J_fare_date"">
//                                </div>
//                            </li>
//                        </ul>
//                    </div>
//                </div> 
//            </div>
//        </div>
//        <div  class=""orderPay blue-line"">
//            <p>
//                店铺合计(含运费)： <span class=""price g_price ""><span>￥</span><em class=""style-middle-bold-red J_ShopTotal"">" + (decAmt + decYf).ToString() + @"</em>
//                </span>
//            </p>
//        </div>
//    </div>
//");
//            } 

//            return sbHtml.ToString();
//        }
         
        public string GetPriceHtml(string strSelId="")
        {
            System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();
            using (msBsc.AppLogic.DataAlc.CBizShpCustomerReceipt odataobj = new AppLogic.DataAlc.CBizShpCustomerReceipt())
            {
                DataSet ds = odataobj.SelectByUserNme(msBsc.SvRef.UserInfo.Operator);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string strtel = ds.Tables[0].Rows[i]["PHONE_NO"].ToString();
                    if (strtel == string.Empty)
                    {
                        strtel += ds.Tables[0].Rows[i]["AREA_CODE"].ToString() + "-" + ds.Tables[0].Rows[i]["LANDLINE_NO"].ToString() + "-" + ds.Tables[0].Rows[i]["EXTENSION_NO"].ToString();
                    }
                    else if (ds.Tables[0].Rows[i]["LANDLINE_NO"].ToString() != string.Empty)
                    {
                        strtel += ","+ ds.Tables[0].Rows[i]["AREA_CODE"].ToString() + "-" + ds.Tables[0].Rows[i]["LANDLINE_NO"].ToString() + "-" + ds.Tables[0].Rows[i]["EXTENSION_NO"].ToString();
                    }

                    bool blchecked = (ds.Tables[0].Rows[i]["IS_DEFAULT"].ToString() == "True" && strSelId == string.Empty || ds.Tables[0].Rows[i]["RECE_ADDRESS_ID"].ToString() == strSelId);
                    string strAddrFull = ds.Tables[0].Rows[i]["ZONE_DESC"].ToString() + ds.Tables[0].Rows[i]["STREET_ADDRESS"].ToString();
                    sbHtml.Append(@" 
            <li class=""J_Addr J_MakePoint clearfix  " + (ds.Tables[0].Rows[i]["IS_DEFAULT"].ToString() == "True" ? "J_DefaultAddr " : "") + (blchecked ? "selected" : "") + @"""  dr-full=""" + strAddrFull.Replace("\"", "") + @""" dr-receipt=""" + ds.Tables[0].Rows[i]["RECEIPT_NME"].ToString() + " " + strtel + @""">
                <s class=""J_Marker marker""></s>
                <span class=""marker-tip"">寄送至</span> 
                <div class=""address-info"">
                    <a href=""javascript:void(0);"" class=""J_Modify modify J_MakePoint""  >修改本地址</a>
                    <input name=""address"" class=""J_MakePoint"" type=""radio"" " + (blchecked ? @"checked=""checked""" : "") + @" value=""" + ds.Tables[0].Rows[i]["RECE_ADDRESS_ID"].ToString() + @""" id=""ckb" + ds.Tables[0].Rows[i]["RECE_ADDRESS_ID"].ToString() + @""" place-id=""" + ds.Tables[0].Rows[i]["PROVINCE_ID"].ToString() + @"""/>
                    <label for=""ckb" + ds.Tables[0].Rows[i]["RECE_ADDRESS_ID"].ToString() + @""" class=""user-address"">
                          " + strAddrFull + @" (" + ds.Tables[0].Rows[i]["RECEIPT_NME"].ToString() + @" 收) <em>" + strtel + @"</em>
                    </label>
                    <em class=""tip hidden"">默认地址</em>
                    <a class=""J_DefaultHandle set-default J_MakePoint hidden"" href=""javascript:void(0);""  >设置为默认收货地址</a>
                    <div class=""msg J_Msg hidden""><p class=""ok naked"">设置成功！</p></div>
                </div>
            </li>");
                } 
            } 
            return sbHtml.ToString();
        }

        private void doSaveOrder()
        {
            //int iOrderSum=int.Parse(this.GetPostHtValue("ORDER_COUNT")==string.Empty?"0":this.GetPostHtValue("ORDER_COUNT"));
            //if (iOrderSum <= 0)
            //{
            //    Alert("未选择商品！");
            //    return;
            //}
            string strRecerptId = this.GetParamHtValue("RECE_ADDRESS_ID");
            if (strRecerptId == string.Empty)
            {
                Alert("未选择收货地址！");
                return;
            }

            using (msBsc.AppLogic.DataAlc.CBizShpOrderForm odataobj = new AppLogic.DataAlc.CBizShpOrderForm())
            {
                DataSet dsAddr = odataobj.DataObj.QueryBySQL("SELECT * FROM SHP_CUSTOMER_RECEIPT WHERE RECE_ADDRESS_ID='" + strRecerptId + "' AND USER_NME='" + msBsc.SvRef.UserInfo.Operator + "'");
                if (dsAddr.Tables[0].Rows.Count <= 0)
                {
                    Alert("未正确选择收货地址！");
                    return;
                }
                using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo objgoods = new AppLogic.DataAlc.CBizShpGoodsInfo())
                {
                    dsList = objgoods.SelectGoodsForConfirmOrder(
                    this.GetParamHtValue("txtGoodsId")
                    , this.GetParamHtValue("txtCartId")
                    , this.GetParamHtValue("txtSrcT")
                    , this.GetParamHtValue("txtPubNId1")
                    , this.GetParamHtValue("txtPubNId2")
                    , int.Parse(this.GetParamHtValue("txtBuyQty"))
                    , this.GetParamHtValue("txtPlaceId"));
                }
                ShowPayAmt(false);
                string strOrderNos = "";
                foreach (string sKey in dicShopLogistAmt.Keys)
                {
                    DataSet ds = new msBsc.Xsd.DataTds.CDmShpOrderForm();
                    DataSet dsItem = new msBsc.Xsd.DataTds.CDmShpOrderFormList();
                    //string strOrderId = "";
                    DataRow[] arrrowtm = dsList.Tables[0].Select("COMM_TENANT_ID='" + sKey + "'");

                    DataSet dsshop = odataobj.DataObj.QueryBySQL(@"
    SELECT
    PROVINCE_ID
    ,CITY_ID
    ,AREA_ID
    ,ZONE_DESC
    ,CONTACTS
    ,CONTACTS_EMAIL
    ,CONTACTS_TEL
    ,CONTACTS_ADDRESS
    ,CONTACTS_PHONE FROM SHP_COMMERCIAL_TENANT_INFO WHERE COMM_TENANT_ID='" + sKey + "'");

                    DataRow drnew = ds.Tables[0].NewRow();
                    drnew["ORDER_FORM_ID"] = odataobj.DataObj.NewID();
                    drnew["USER_NME"] = msBsc.SvRef.UserInfo.Operator;
                    drnew["ORDER_FORM_NO"] = msBsc.SvRef.ApplicationConst.Const.GeneratelongId().ToString();
                    drnew["COMM_TENANT_ID"] = sKey;
                    //DataSet dsDealer = odataobj.DataObj.QueryBySQL("SELECT COMM_TENANT_NME,USER_NME FROM SHP_COMMERCIAL_TENANT_INFO WHERE COMM_TENANT_ID='" + drnew["COMM_TENANT_ID"].ToString() + "' ");
                    //if (dsDealer.Tables[0].Rows.Count <= 0)
                    //{
                    //    Alert("传入的参数错误，商家信息未找到！");
                    //    return;
                    //}
                    if (arrrowtm[0]["USER_NME"].ToString().ToUpper() == msBsc.SvRef.UserInfo.Operator.ToUpper())
                    {
                        Alert("不能自己购买自己的商品！");
                        return;
                    }

                    drnew["COMM_TENANT_NME"] = arrrowtm[0]["COMM_TENANT_NME"];
                    drnew["COMM_USER_NME"] = arrrowtm[0]["USER_NME"];
                    drnew["FROM_PROVINCE_ID"] = dsshop.Tables[0].Rows[0]["PROVINCE_ID"];
                    drnew["FROM_CITY_ID"] = dsshop.Tables[0].Rows[0]["CITY_ID"];
                    drnew["FROM_AREA_ID"] = dsshop.Tables[0].Rows[0]["AREA_ID"];
                    drnew["FROM_ZONE_DESC"] = dsshop.Tables[0].Rows[0]["ZONE_DESC"];
                    drnew["FROM_STREET_ADDRESS"] = dsshop.Tables[0].Rows[0]["CONTACTS_ADDRESS"];
                    drnew["FROM_SENDER_NME"] = dsshop.Tables[0].Rows[0]["CONTACTS"];
                    drnew["FROM_PHONE_NO"] = dsshop.Tables[0].Rows[0]["CONTACTS_PHONE"];
                    drnew["FROM_LANDLINE_NO"] = dsshop.Tables[0].Rows[0]["CONTACTS_TEL"];


                    drnew["TO_PROVINCE_ID"] = dsAddr.Tables[0].Rows[0]["PROVINCE_ID"];
                    drnew["TO_CITY_ID"] = dsAddr.Tables[0].Rows[0]["CITY_ID"];
                    drnew["TO_AREA_ID"] = dsAddr.Tables[0].Rows[0]["AREA_ID"];
                    drnew["TO_ZONE_DESC"] = dsAddr.Tables[0].Rows[0]["ZONE_DESC"];
                    drnew["TO_STREET_ADDRESS"] = dsAddr.Tables[0].Rows[0]["STREET_ADDRESS"];
                    drnew["TO_ZIP_CODE"] = dsAddr.Tables[0].Rows[0]["ZIP_CODE"];
                    drnew["TO_RECEIPT_NME"] = dsAddr.Tables[0].Rows[0]["RECEIPT_NME"];
                    drnew["TO_PHONE_NO"] = dsAddr.Tables[0].Rows[0]["PHONE_NO"];
                    if (dsAddr.Tables[0].Rows[0]["LANDLINE_NO"].ToString() != string.Empty)
                    {
                        drnew["TO_LANDLINE_NO"] = dsAddr.Tables[0].Rows[0]["AREA_CODE"].ToString() + "-" + dsAddr.Tables[0].Rows[0]["LANDLINE_NO"].ToString() + (dsAddr.Tables[0].Rows[0]["EXTENSION_NO"].ToString() != string.Empty ? "-" + dsAddr.Tables[0].Rows[0]["EXTENSION_NO"].ToString() : "");
                    }
                    else
                    {
                        drnew["TO_LANDLINE_NO"] = "";
                    } 
                    drnew["DELIVER_TYPE_CID"] = "普通快递";

                    drnew["BUY_MEMO"] = this.GetParamHtValue("BUY_MEMO_" + sKey);

                    //int iItemSum = int.Parse(this.GetPostHtValue("ORDER_ITEM_COUNT_" + i.ToString()) == string.Empty ? "0" : this.GetPostHtValue("ORDER_ITEM_COUNT_" + i.ToString()));
                    ////string strGdIds = "";
                    //string strNormsIds = "";
                    //for (int r = 0; r < iItemSum; r++)
                    //{
                    //    //strGdIds += strGdIds == string.Empty ? this.GetPostHtValue("GOODS_ID_" + i.ToString() + "_" + r.ToString()) : "','" + this.GetPostHtValue("GOODS_ID_" + i.ToString() + "_" + r.ToString());
                    //    strNormsIds += strNormsIds == string.Empty ? this.GetPostHtValue("PUB_NORMS_ID_" + i.ToString() + "_" + r.ToString()) : "','" + this.GetPostHtValue("PUB_NORMS_ID_" + i.ToString() + "_" + r.ToString());
                    //}

                    //DataSet dsGdList = odataobj.DataObj.QueryBySQL("SELECT GOODS_ID,GOODS_NME FROM SHP_GOODS_INFO WHERE GOODS_ID IN ('" + strGdIds + "') ");
                    //                        DataSet dsNmList = odataobj.DataObj.QueryBySQL(@"
                    //    SELECT 
                    //    A.GOODS_ID
                    //    ,A.GOODS_NME
                    //    ,I.IMG_URL
                    //    ,NORMS_DESC=(CASE WHEN B.PUB_NORMS_NME1<>'' THEN  ' '+(CASE WHEN ISNULL(D.NORMS_NME1,'')<>'' THEN D.NORMS_NME1 ELSE '分类' END) + ':'+ B.PUB_NORMS_NME1 ELSE '' END)
                    //			    + (CASE WHEN B.PUB_NORMS_NME2<>'' THEN  ','+(CASE WHEN ISNULL(D.NORMS_NME2,'')<>'' THEN D.NORMS_NME2 ELSE '型号' END) + ':'+ B.PUB_NORMS_NME2 ELSE '' END)+'  '
                    //    ,B.GOODS_STRIKE_PRICE
                    //    ,A.FREIGHT
                    //    ,B.PUB_NORMS_ID
                    //    FROM SHP_GOODS_NORMS_PUBLIC B
                    //    LEFT OUTER JOIN SHP_GOODS_INFO A ON A.GOODS_ID=B.GOODS_ID
                    //    LEFT OUTER JOIN SHP_GOODS_TYPE_LEVEL_THREE D ON A.LEVEL_THREE_ID=D.LEVEL_THREE_ID
                    //    LEFT OUTER JOIN SHP_GOODS_IMG I ON A.GOODS_ID=I.GOODS_ID AND I.SEQ_NUM=0
                    //    WHERE B.PUB_NORMS_ID IN ('" + strNormsIds + @"')");
                    decimal decTotal = 0, decAmt = 0;
                    int iRvcScoreTotal = 0;
                    string strGoodsNme = "";
                    for (int r = 0; r < arrrowtm.Length; r++)
                    {
                        string strGoodsId = arrrowtm[r]["GOODS_ID"].ToString();
                        //DataRow[] arrrowtem1 = dsNmList.Tables[0].Select("GOODS_ID='" + strGoodsId + "'");
                        //if (arrrowtem1.Length <= 0)
                        //{
                        //    continue;
                        //}
                        //int iGoodsQty = int.Parse(this.GetPostHtValue("GOODS_QTY_" + i.ToString() + "_" + r.ToString()) == string.Empty ? "1" : this.GetPostHtValue("GOODS_QTY_" + i.ToString() + "_" + r.ToString()));
                        DataRow dritem = dsItem.Tables[0].NewRow();
                        dritem["ORDER_LIST_ID"] = odataobj.DataObj.NewID();
                        dritem["ORDER_FORM_ID"] = drnew["ORDER_FORM_ID"];
                        dritem["SEQ_NUM"] = r;
                        dritem["GOODS_ID"] = strGoodsId;
                        dritem["GOODS_NME"] = arrrowtm[r]["GOODS_NME"];
                        dritem["IMG_URL"] = arrrowtm[r]["IMG_URL"];
                        dritem["PUB_NORMS_ID"] = arrrowtm[r]["PUB_NORMS_ID"];
                        dritem["NORMS_DESC"] = arrrowtm[r]["NORMS_DESC"].ToString().Substring(1);
                        if (arrrowtm[r]["IS_DEL"].ToString() == "1")
                        {
                            this.ExecJScript("window.location.reload(true) ;");
                            throw new Exception("商品已失效或库存不足，无法确认订单，请返回重新选择");
                        }
                        dritem["GOODS_QTY"] = arrrowtm[r]["GOODS_QTY"];
                        dritem["GOODS_STRIKE_PRICE"] = arrrowtm[r]["GOODS_STRIKE_PRICE"];
                        dritem["GOODS_STRIKE_SCORE"] = arrrowtm[r]["GOODS_STRIKE_SCORE"];

                        strGoodsNme += strGoodsNme == string.Empty ? dritem["GOODS_NME"].ToString() : "," + dritem["GOODS_NME"].ToString();
                        decAmt += (decimal)arrrowtm[r]["GOODS_AMT"];
                        iRvcScoreTotal += (int)arrrowtm[r]["SCORE_NUM"] * (int)dritem["GOODS_QTY"];
                        //decYf += decimal.Parse(arrrowtem1[0]["FREIGHT"].ToString() == string.Empty ? "0.00" : arrrowtem1[0]["FREIGHT"].ToString());
                        dsItem.Tables[0].Rows.Add(dritem);
                    }
                    decTotal += (decAmt + dicShopLogistAmt[sKey]);
                    drnew["GOODS_AMT"] = decAmt;
                    drnew["LOGISTICS_AMT"] = dicShopLogistAmt[sKey];
                    drnew["DISCOUNT_AMT"] = 0M;
                    drnew["PAYABLE_AMT"] = decTotal;

                    if (strGoodsNme.Length > 25)
                    {
                        strGoodsNme = strGoodsNme.Substring(0, 25);
                    }
                    drnew["ORDER_FORM_NME"] = strGoodsNme;

                    drnew["PAID_SCORE_QTY"] = int.Parse(this.GetParamHtValue("txtPaidScoreQty") == string.Empty ? "0" : this.GetParamHtValue("txtPaidScoreQty"));
                    drnew["PAID_SCORE_AMT"] = (int)drnew["PAID_SCORE_QTY"] * msBsc.SvRef.SysConst.decScoreUsePrice();
                    drnew["RCV_SCORE_QTY"] = iRvcScoreTotal;

                    drnew["PAID_AMT"] = (decimal)drnew["PAYABLE_AMT"] - (decimal)drnew["PAID_SCORE_AMT"];
                    drnew["PAID_MODE_CID"] = "";
                    drnew["TRADE_STATUS_TXT"] = "等待买家付款";
                    drnew["AFTER_SVC_STATUS_TXT"] = "";
                    ds.Tables[0].Rows.Add(drnew);

                    strOrderNos += strOrderNos == string.Empty ? drnew["ORDER_FORM_NO"].ToString() : "," + drnew["ORDER_FORM_NO"].ToString();


                    System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpOrderFormList objItem = new AppLogic.DataAlc.CBizShpOrderFormList())
                        {
                            objItem.Update(dsItem);
                        }
                        odataobj.Update(ds);
                        //using (msBsc.AppLogic.DataAlc.CBizSysUser ouser = new AppLogic.DataAlc.CBizSysUser())
                        //{
                        //    ouser.UpdateOrderStatistic(msBsc.SvRef.UserInfo.Operator);
                        //}

                        if (this.GetParamHtValue("txtCartId") != string.Empty)
                        {
                            odataobj.DataObj.ExecuteBySQL("DELETE SHP_CUSTOMER_CART WHERE USER_NME='"+msBsc.SvRef.UserInfo.Operator+"' AND CART_ORDER_ID IN ('" + this.GetParamHtValue("txtCartId").Replace(",","','") + "')");
                        }

                        ts.Complete();
                    }
                }

                this.ExecJScript("layer.msg('已成功提交订单！',1,{type:1,shade:false});");
                this.ExecJScript("window.location.href = '/c_PayCashier.htm?ID=" + strOrderNos + "';");
            }
        }

        public override void DoAction()
        {
            if (this.strAction == "updateaddress")
            { 
                this.ExecJScript("$('#address-list').html('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(GetPriceHtml(GetParamHtValue("SEL_ID"))) + "');");
                this.ExecJScript("updateorderaddr();");
            }
            else if (this.strAction == "doloadGoodsList")
            {
                ShowPayAmt();
                loadGoodsList(
                    this.GetParamHtValue("txtGoodsId")
                    , this.GetParamHtValue("txtCartId")
                    , this.GetParamHtValue("txtSrcT")
                    , this.GetParamHtValue("txtPubNId1")
                    , this.GetParamHtValue("txtPubNId2")
                    , int.Parse(this.GetParamHtValue("txtBuyQty"))
                    , this.GetParamHtValue("txtPlaceId"));
                if (this.GetParamHtValue("RECE_ADDRESS_ID") != string.Empty)
                {
                    this.ExecJScript("$('#J_Go').removeClass('btn-go-disabled');");
                }
                DataRow[] arrrowtem2 = dsList.Tables[0].Select("IS_DEL='1'");
                if (arrrowtem2.Length > 0)
                {
                    this.ExecJScript("$('#J_Go').removeClass('btn-go-disabled').addClass('btn-go-disabled');");
                    this.ExecJScript("$('#divErrShow').html('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson("商品已失效或库存不足，无法确认订单，请返回重新选择！") + "');");
                }
            }
            else if (this.strAction == "doSaveOrder")
            {
                doSaveOrder();
            }
        }
    }
}